﻿using System;
using System.Collections.Specialized;

namespace ForumEngine.Security
{
    public static class ParameterHelper
    {
        public static bool GetBooleanValue(NameValueCollection config, string valueName, bool defaultValue)
        {
            var valueText = config[valueName];
            if (string.IsNullOrEmpty(valueText))
            {
                return defaultValue;
            }
            bool ret;
            return !bool.TryParse(valueText, out ret) ? defaultValue : ret;
        }

        public static int GetIntValue(NameValueCollection config, string valueName, int defaultValue, int maxValue, bool acceptNegative)
        {
            var valueText = config[valueName];
            if (string.IsNullOrEmpty(valueText))
            {
                return defaultValue;
            }
            int ret;
            if (!int.TryParse(valueText, out ret))
            {
                return defaultValue;
            }
            if (ret > maxValue)
            {
                return maxValue;
            }
            return ret;
        }

        public static T GetEnumValue<T>(NameValueCollection config, string valueName, T defaultValue) where T: struct
        {
            var valueText = config[valueName];
            if (string.IsNullOrEmpty(valueText))
            {
                return defaultValue;
            }

            T ret;
            if (!Enum.TryParse(valueText, true, out ret))
            {
                return defaultValue;
            }

            return ret;
        }

        public static bool ValidateParameter(string parameter, int maxLength, bool canBeEmpty)
        {
            if (!canBeEmpty && string.IsNullOrEmpty(parameter))
            {
                return false;
            }

            if (maxLength > 0 && (parameter != null && parameter.Length > maxLength))
            {
                return false;
            }

            return true;
        }
    }
}